import dayjs from 'dayjs'
// 打印机纸宽58mm，页的宽度384，字符宽度为1，每行最多盛放32个字符
const PAGE_WIDTH = 384
const MAX_CHAR_COUNT_EACH_LINE = 32
const FEED = 35
const LINE_SPACE_CLASS = {
  0: 0,
  1: 10,
  2: 20,
  3: 30,
  4: 40,
  5: 50,
  6: 60,
}
/**
 * 用字符填充一整行
 * @param {string} fillWith 填充字符
 * @param {number} fontWidth 字符宽度 1/2
 */
function fillLine(fillWith = '-', fontWidth = 1) {
  const lineWidth = MAX_CHAR_COUNT_EACH_LINE / fontWidth;
  return new Array(lineWidth).fill(fillWith.charAt(0)).join('')
}

/**
 * @param str
 * @returns {boolean} str是否全是中文
 */
function isChinese(str) {
  return /^[\u4e00-\u9fa5]$/.test(str);
}

/**
 * 返回字符串宽度(1个中文=2个英文字符)
 * @param str
 * @returns {number}
 */
function getStringWidth(str) {
  let width = 0;
  for (let i = 0, len = str.length; i < len; i++) {
    width += isChinese(str.charAt(i)) ? 2 : 1;
  }
  return width;
}

export const loopPrint = (command, list, maxLength) => {
  let p = 0
  let length = 0
  list.forEach((v, i) => {
    length = length + getStringWidth(v)
    if (length >= maxLength) p = i
  })
  command.setText(`${list.splice(0, p || maxLength).join("")}`);
  command.setPrint()
  if (list.length > 0) loopPrint(command, list, maxLength)
}

/**
 * 初始化
 * @param {*} command 
 */
export const initData = (command) => {
  command.bold(0);
  command.setFontSize(0);
  command.setSelectJustification(0); //居左
}
export default class util {
  constructor(lineSpace) {
    this.PAGE_WIDTH = 384
    this.MAX_CHAR_COUNT_EACH_LINE = 32
    this.LINE_SPACE = lineSpace && LINE_SPACE_CLASS[lineSpace] || 10
    this.FEED = 35
  }

  printShopName(command, shopName) {
    command.bold(1); //加粗
    command.setFontSize(16); //字体大小
    command.setSelectJustification(1) //居中
    command.setText(shopName || "");
    command.rowSpace(60);
    command.setPrint();
  }

  /**
 * 打印区域信息
 * @param {*} command 
 * @param {*} areaName 
 */
  printAreaInfo = (command, areaName) => {
    command.init()
    command.bold(1); //加粗
    command.setFontSize(16); //字体大小
    command.setSelectJustification(1) //居中
    command.setText(areaName || '店内');
    command.rowSpace(60);
    command.setPrint();
  }

  /**
 * 头部信息
 * @param {*} command 
 * @param {*} date 
 * @param {*} no 
 */
  printHeader = (command, date, no) => {
    command.init()
    command.rowSpace(this.LINE_SPACE)
    /**下单时间 */
    command.setText(`下单时间：${dayjs(date).format('YYYY-MM-DD HH:mm:ss')}`);
    command.setPrint();
    // command.init()
    /**订单编号 */
    command.setText(`订单编号：${no}`);
    command.setPrint();
  }

  /**
   * 打印商品信息
   * @param {*} command 
   * @param {*} orderGoods 
   */
  printGoods = (command, orderGoods) => {
    const goodsPos = 0
    const numPos = 230
    const pricePos = 305

    command.init()
    command.rowSpace(this.LINE_SPACE)
    /**表头 */
    // command.rowSpace(this.LINE_SPACE)
    command.setAbsolutePrintPosition(goodsPos);
    command.setText("商品");
    command.setAbsolutePrintPosition(numPos);
    command.setText("数量");
    command.setAbsolutePrintPosition(pricePos);
    command.setText("单价");
    command.setPrintAndFeed(FEED)
    orderGoods.forEach((goods, index) => {
      let maxWidth = numPos / PAGE_WIDTH * MAX_CHAR_COUNT_EACH_LINE // 显示的最大字符数
      let titleList = goods.title.split("");
      let spliceNum = 0
      let length = 0
      for (let i = 0; i < titleList.length; i++) {
        const element = titleList[i];
        length = length + getStringWidth(element)
        if (length >= maxWidth) {
          spliceNum = i
          break
        }
      }
      command.setAbsolutePrintPosition(goodsPos);
      command.setText(`${titleList.splice(0, spliceNum || numPos).join("")}`);
      command.setAbsolutePrintPosition(numPos + 5);
      command.setText(`${goods.num}`);
      command.setAbsolutePrintPosition(pricePos + 5);
      command.setText(`${goods.price}`);
      command.setPrint()
      // 标题过长换行
      if (titleList.length > 0) {
        loopPrint(command, titleList, maxWidth)
      }
      /**打印商品属性 */
      if (goods.props.length > 0 || (goods.spec && goods.spec.length > 0)) {
        let props = (goods.props || []).map(v => v.v[0])
        let specs = (goods.spec || []).map(v => v.value)
        let propSpecs = [...specs, ...props].join('/')
        command.setAbsolutePrintPosition(goodsPos);
        command.setText(`${propSpecs}`);
        command.setPrint()
      }
      if (index < orderGoods.length - 1) {
        // command.setPrintAndFeed()
        // command.setPrint()
        command.init()
        command.rowSpace(this.LINE_SPACE)
        console.log('还没完');
      } else {
        console.log('最后一行');
        command.setPrintAndFeed(0)
      }
    })
  }

  /**
 * 备注信息
 * @param {*} command 
 * @param {*} buyerRemark 
 */
  printRemarkData = (command, buyerRemark) => {
    command.init()
    command.rowSpace(this.LINE_SPACE)
    command.setText(`备注：${buyerRemark || '无'}`);
    command.setPrint();
  }

  /**
 * 打包费 外送费
 * @param {*} command 
 * @param {*} config 
 */
  printDeliveryFee = (command, config) => {
    command.init()
    command.rowSpace(this.LINE_SPACE)
    command.setAbsolutePrintPosition(0);
    command.setText(`打包费`);
    command.setAbsolutePrintPosition(280);
    command.setText(`${config.boxFee && config.boxFee.toFixed(2) || '0.00'}`);
    command.setPrint()
    command.setAbsolutePrintPosition(0);
    command.setText(`外送费`);
    command.setAbsolutePrintPosition(280);
    command.setText(`${config.deliveryFee && config.deliveryFee.toFixed(2) || '0.00'}`);
    command.setPrint()
  }

  /**
 * 外送信息
 * @param {*} command 
 * @param {*} deliveryInfo 
 */
  printDeliveryInfo = (command, deliveryInfo) => {
    let sexMap = {
      0: "先生",
      1: "女士"
    }
    command.init()
    command.rowSpace(this.LINE_SPACE)
    command.setText(`收货人：${deliveryInfo && deliveryInfo.name} ${sexMap[deliveryInfo && deliveryInfo.sex]}`);
    command.setPrint();
    command.setText(`联系电话：${deliveryInfo && deliveryInfo.phone}`);
    command.setPrint();
    command.setText(`配送地址：${deliveryInfo && deliveryInfo.address} ${deliveryInfo && deliveryInfo.addressDetail}`);
    command.init()
    command.setPrint();
  }

  /**
 * 订单总额
 * @param {*} command
 * @param {*} total 
 */
  printTotal = (command, total) => {
    command.init()
    // command.setAbsolutePrintPosition(0); //居左
    command.setText(`实收:￥`);
    command.bold(1); //加粗
    command.setFontSize(16); //字体大小
    command.setSelectJustification(2); //居右
    command.setText(`${total.toFixed(2)}`); // 总价格
    command.setPrint();
    command.bold(0); //加粗
    command.setFontSize(0); //字体大小
    command.setPrintAndFeedRow(2);
  }

  /**
 * 打印虚线
 * @param {*} command 
 */
  printDotted = (command) => {
    command.init()
    command.rowSpace(this.LINE_SPACE)
    command.setText(fillLine('…', 2));
    command.setPrint();
  }

  /**
 * 打印二维码
 * @param {*} command 
 */
  printCode = (command, data) => {
    command.init()
    command.setSelectSizeOfModuleForQRCode(8)
    command.setSelectErrorCorrectionLevelForQRCode(50)
    command.setStoreQRCodeData(data)
    command.setSelectJustification(1)
    command.setPrintQRCode();
    command.setPrintAndFeedRow(4);
  }
}
